﻿using M.WWHours.API.Command.WorkerListCommand;
using M.WWHours.Domain.Dto;
using M.WWHours.Domain.Model;
using M.WWHours.Repository.WWHoursInterface;
using MediatR;

namespace M.WWHours.API.CommandHandlers.WorkerListCommandHandler
{
    /// <summary>
    /// 显示工人列表命令处理器
    /// </summary>
    public class ShowWorkerListCommandHandler : IRequestHandler<ShowWorkerListCommand, WorkerListDto<WorkerList>>
    {
        /// <summary>
        /// 工人列表仓储接口
        /// </summary>
        protected readonly IWorkerListRepository workerListRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="workerListRepository">工人列表仓储接口</param>
        public ShowWorkerListCommandHandler(IWorkerListRepository workerListRepository)
        {
            this.workerListRepository = workerListRepository;
        }

        /// <summary>
        /// 处理显示工人列表命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<WorkerListDto<WorkerList>> Handle(ShowWorkerListCommand request, CancellationToken cancellationToken)
        {
            var list = from a in await workerListRepository.GetAllAsync()
                       where !a.IsDeleted
                       select new WorkerList()
                       {
                           WorkerListId = a.WorkerListId,
                           WorkerNumber = a.WorkerNumber,
                           WorkersName = a.WorkersName,
                           PhoneNumber = a.PhoneNumber,
                           Gender = a.Gender,
                           Department = a.Department,
                           TeamsAndGroups = a.TeamsAndGroups,
                           Status = a.Status,
                       };

            if (!string.IsNullOrEmpty(request.WorkerNumber))
            {
                list = list.Where(x => x.WorkerNumber.Contains(request.WorkerNumber));
            }

            if (!string.IsNullOrEmpty(request.WorkersName))
            {
                list = list.Where(x => x.WorkersName.Contains(request.WorkersName));
            }

            if (!string.IsNullOrEmpty(request.Status))
            {
                list = list.Where(x => x.Status.Contains(request.Status));
            }

            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }

            if (request.PageSize == null)
            {
                request.PageSize = 15;
            }

            WorkerListDto<WorkerList> page = new WorkerListDto<WorkerList>();
            page.TotalCount = list.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = list.OrderByDescending(x => x.CreatedDate).Skip((int)request.PageIndex - 1).Take((int)request.PageSize).ToList();
            return page;

        }
    }
}
